﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Bridge.Shared;
using Bridge.Shared.Helper;
using Bridge.Shared.Models;
using Bridge.Workflow.Domain;
using Bridge.Workflow.Domain.Workflows;
using Bridge.Workflow.Roles.Dto;
using Bridge.Workflow.Users;
using Bridge.Workflow.Users.Dto;
using Bridge.Workflow.Users.Request;
using Microsoft.Extensions.Configuration;
using Users;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Identity;
using Volo.Abp.Users;

namespace Bridge.Workflow.Application
{
    /// <summary>
    /// 
    /// </summary>
    public class UserAppService : ApplicationService, IUserAppService
    {
        private readonly ICurrentUser _currentUser;
        private readonly string _authorityUrl;
        public static IConfiguration Config { get; set; }
        private readonly IUserService _userService;
        

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userRepository"></param>
        /// <param name="config"></param>
        public UserAppService(
            ICurrentUser currentUser, IUserService userManager, IConfiguration config)
        {
            this._currentUser = currentUser;
            Config = config;
            this._authorityUrl = Config["RemoteServices:SystemService:BaseUrl"];
            this._userService = userManager;
        }


        public class ResultLoginInfo
        {

            public int loginResult { get; set; }
            public string loginResultStr { get; set; }
            public string token { get; set; }
        }

        public async Task<string> Authenticate(UserLoginInfoRequest request)
        {
            var login = new { phone = request.UserNameOrEmailAddress, password = request.Password, request.RememberMe };
            ////1.验证登录接口是否成功
            var responseResult = HttpHelper.ServiceRequest($"{_authorityUrl}/api/sys/v2/userAccount/login", login);
            var loginResult = responseResult.FromJsonString<ResponseResult<ResultLoginInfo>>();
            return loginResult.Result.token;
        }


        public class ResultUserInfo
        {
            public Guid id { get; set; }
            public string userName { get; set; }

            public string name { get; set; }

            public string surname { get; set; }

            public string email { get; set; }

            public bool isDeleted { get; set; }

            public DateTime? lastLoginTime { get; set; }

            public DateTime creationTime { get; set; }

            public List<string> rolesName { get; set; }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ResponseResult<UserDto>> GetAsync(string userId)
        {
            if (userId.IsNullOrEmpty()) userId = _currentUser.Id.ToString();
            string url = $"{_authorityUrl}/api/sys/v2/users/getById?id={userId}";
            var responseResult = await HttpHelper.SendAsync(url, HttpMethod.Get);
            if (responseResult.Code == 0)
            {
                return ResponseResult<UserDto>.Fail(responseResult.Message);
            }
            var user = responseResult.Result.FromJsonString<ResponseResult<ResultUserInfo>>();

            return ResponseResult<UserDto>.Success("", new UserDto
            {
                UserName = user.Result.userName,
                EmailAddress = user.Result.email,
                IsActive = !user.Result.isDeleted,
                CreationTime = user.Result.creationTime,
                Name = user.Result.name,
                Surname = user.Result.surname,
                Id = user.Result.id,
                LastLoginTime = user.Result.lastLoginTime,
                RoleNames = user.Result.rolesName
            });
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResponseResult<GetCurrentLoginInformationsOutput> GetCurrentLoginInformations()
        {
            //var userpage = GetAsync(string.Empty).Result;
            //var user = new UserLoginInfoDto
            //{
            //    Name = userpage.Result.Name,
            //    Surname = userpage.Result.Surname,
            //    UserName = userpage.Result.UserName,
            //    EmailAddress = userpage.Result.EmailAddress
            //};
            //var output = new GetCurrentLoginInformationsOutput
            //{
            //    Application = new ApplicationInfoDto
            //    {
            //        Version = "2.0",
            //        ReleaseDate = DateTime.Now,
            //        Features = new Dictionary<string, bool>()
            //    },
            //    Tenant = new TenantLoginInfoDto(),
            //    User = user


            //};
            return ResponseResult<GetCurrentLoginInformationsOutput>.Success("", null);
        }

        public class ResultRolesInfo
        {
            public string id { get; set; }
            public string name { get; set; }
            public string normalizedName { get; set; }
        }

        /// <summary>
        /// 获取全部角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ListResponseResult<RoleDto>> GetRoles(SearchUserInput input)
        {

            var login = new { name = input.Keyword, pageIndex = input.PageIndex, pageSize = input.PageSize };
            ////1.验证登录接口是否成功
            var responseResult = HttpHelper.ServiceRequest($"{_authorityUrl}/api/sys/v2/baserole/GetList", login);
            var roleResult = responseResult.FromJsonString<ResponseResult<List<ResultRolesInfo>>>();
            return ListResponseResult<RoleDto>.Success(string.Empty, roleResult.Result.Select(x => new RoleDto
            {
                Id = x.id,
                Name = x.name,
                DisplayName = x.name
            }).ToList());
        }

        /// <summary>
        /// 获取全部角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ListResponseResult<UserDto>> GetUser(SearchUserInput input)
        {
            var login = new { userName = input.Keyword, pageIndex = input.PageIndex, pageSize = input.PageSize, status = 0 };
            ////1.验证登录接口是否成功
            var responseResult = HttpHelper.ServiceRequest($"{_authorityUrl}/api/sys/v2/users/getUserList", login);
            var roleResult = responseResult.FromJsonString<ResponseResult<List<ResultUserInfo>>>();

            return ListResponseResult<UserDto>.Success(string.Empty, roleResult.Result.Select(user => new UserDto
            {
                UserName = user.userName,
                EmailAddress = user.email,
                IsActive = !user.isDeleted,
                CreationTime = user.creationTime,
                Name = user.name,
                Surname = user.surname,
                Id = user.id,
                LastLoginTime = user.lastLoginTime,
                RoleNames = user.rolesName
            }).ToList());
        }

        /// <summary>
        /// 根据单当前节点获取下一步要审批的用户
        /// </summary>
        /// <param name="nextNode"></param>
        /// <returns></returns>
        public async Task<List<IdentityUserDto>> GetApprovalUserList(WorkflowNode nextNode, PersistedWorkflow workflow)
        {
            if (_currentUser == null)
            {
                throw new UserFriendlyException("用户未登录!");
            }
            var res = new List<IdentityUserDto>();
            var stepBodyName = nextNode.StepBody.Name;

            switch (stepBodyName)
            {
                case "FixedRoleAudit"://获取角色审批的用户
                    var roleId = nextNode.StepBody.Inputs["RoleName"].Value?.ToString();
                    var userIdentityName = await _userService.WfGetAsyncById(_currentUser.Id ?? Guid.Empty);
       

                    res = await _userService.GetUserListByRoleName(Guid.Parse(roleId));

                    break;
                case "FixedCreateUserAudit"://
                    var user = await _userService.WfGetAsyncById(workflow.CreatorId.Value);
                    res.Add(user);
                    break;
            }
            return res;
        }
    }
}
